package com.example.light.web.personal.service.impl;

import com.example.light.common.GlobalConstant;
import com.example.light.common.exception.GlobalException;
import com.example.light.common.result.CodeMsg;
import com.example.light.redis.RedisService;
import com.example.light.redis.UserKey;
import com.example.light.web.personal.service.PersonalService;
import com.example.light.web.personal.vo.UserVO;
import com.example.light.web.system.dao.DepartmentMapper;
import com.example.light.web.system.dao.RoleMapper;
import com.example.light.web.system.dao.UserMapper;
import com.example.light.web.system.dao.UserRoleMapper;
import com.example.light.web.system.entity.Department;
import com.example.light.web.system.entity.Role;
import com.example.light.web.system.entity.User;
import com.example.light.web.system.entity.UserRole;
import com.example.light.web.system.service.UserService;
import com.google.common.io.Files;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Service
public class PersonalServiceImpl implements PersonalService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public UserVO showUserVO(User user) {
        UserRole role = userRoleMapper.selectUserRole(user.getUserId());
        Department department = null;
        if (user.getDeptId() != null) {
            department = departmentMapper.selectByPrimaryKey(user.getDeptId());
        }
        UserVO userVO = new UserVO();
        userVO.setUserId(user.getUserId()).setAvator(user.getUserAvator()).setEmail(user.getUserEmail())
                .setFavor(user.getUserFavor()).setIntro(user.getUserDescription())
                .setPhone(user.getUserPhone()).setUserName(user.getUserName());
        userVO.setSex(user.getUserGender());
        if (department != null) {
            userVO.setDeptName(department.getDeptName());
        }
        if (role != null) {
            Integer roleId = role.getRoleId();
            Role realRole = roleMapper.selectByPrimaryKey(roleId);
            userVO.setRoleName(realRole.getRoleName());
        }
        return userVO;
    }

    @Override
    public void updateUserInfo(UserVO userVO, HttpServletRequest request, MultipartFile file) {
        User user = new User();
        user.setUserPhone(userVO.getPhone());
        user.setUserId(userVO.getUserId());
        try {
            userMapper.updateByPrimaryKeySelective(user);
        } catch (Exception e) {
            throw new GlobalException(CodeMsg.SystemCodeMsg.PHONE_EXISTS);
        }
        user.setUserEmail(userVO.getEmail());
        try {
            userMapper.updateByPrimaryKeySelective(user);
        } catch (Exception e) {
            throw new GlobalException(CodeMsg.PersonalCodeMsg.EMAIL_EXISTS);
        }
        user.setUserManipulateTime(new Date());
        user.setUserAvator(userVO.getAvator());
        user.setUserDescription(userVO.getIntro());
        user.setUserFavor(userVO.getFavor());
        user.setUserGender(userVO.getSex());
        user.setUserName(userVO.getUserName());
        String filePath = uploadFile(request, user.getUserPhone(), file);
        user.setUserAvator(filePath);
        userMapper.updateByPrimaryKeySelective(user);
        String token = getCookie(request, GlobalConstant.COOKIE_NAME);
        redisService.set(UserKey.token, token, user);
    }

    private String getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    private String uploadFile(HttpServletRequest request, String userPhone, MultipartFile file) {
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//        int end = path.lastIndexOf("target");
//        String storePath = path.substring(1, end);
        path = path + "static";
        String filename = file.getOriginalFilename();
        String dbPath = File.separator + "file" + File.separator + userPhone + File.separator + filename;
        String res = dbPath.replace(File.separator, "/");
        File storeFile = new File(path + dbPath);
        try {
            if (!storeFile.exists()) {
                storeFile.getParentFile().mkdirs();
                storeFile.createNewFile();
            }
            Files.write(file.getBytes(), storeFile);

        } catch (IOException e) {
            throw new GlobalException(CodeMsg.PersonalCodeMsg.FILE_UPLOAD_FAIL);
        }
        return res;
    }
}
